package cn.edu.xaut.mybatisers.mall.ServiceImp;

import cn.edu.xaut.mybatisers.mall.Service.ImageService;
import org.springframework.stereotype.Service;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.awt.image.RenderedImage;
import java.io.*;
import java.nio.file.Files;

@Service
public class ImageServiceImp implements ImageService {
    @Override
    public void getImageByName(String imageName, HttpServletResponse response) throws IOException {
        File image_file = new File(System.getProperty("pictureSavePath") + "/" +imageName);
        String name_suffix = image_file.getName().substring(image_file.getName().indexOf(".")+1);
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setContentType("image/" + name_suffix);
        if (!image_file.exists()){
            image_file = new File(System.getProperty("user.dir") + "/static/404.png");
            response.setContentType("image/png");
        }
        byte[] bytes = new byte[1024];
        OutputStream os = response.getOutputStream();
        FileInputStream fis = new FileInputStream(image_file);
        while ((fis.read(bytes)) != -1) {
            os.write(bytes);
            os.flush();
        }
    }
}
